//
//  gouwuCarVC.m
//  YaoHeAPP
//
//  Created by xyh on 16/3/15.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "gouwuCarVC.h"

#import "Masonry.h"

#import "SVPullToRefresh.h"
#import "Controller.h"

#import "gouwucartModel.h"

#import "labelview.h"

#import "QualityHeadView.h"

#import "gouwuCarCell.h"


#import "TongYong.h"

#import "TPKeyboardAvoidingTableView.h"


#import "SureOrderVC.h"

#import "CreateCompanyVC.h"

#import "zijinzhanghuVC.h"

#import "Tool.h"

#import "JSONKit.h"

#import "NSString+formatWithFloat.h"
#define bgVCcolor [UIColor colorWithRed:235.f/255.f green:235.f/255.f blue:244.f/255.f alpha:1]
#define Color153  [UIColor colorWithRed:80.f/255.f green:80.f/255.f blue:80.f/255.f alpha:1]
#define screenWidth self.view.frame.size.width
#define screenHeight self.view.frame.size.height

@interface gouwuCarVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,labelviewdelegate,QualityHeadViewDelegate>
{
//段头数组
    NSArray *headArray;
//内容数组
    NSMutableArray *cellArray;
    
    labelview *la;

    NSMutableDictionary *dicdata;//定义大字典
    
     NSString *dan;
    
    UIButton *quanxuanBUt;//全选按钮
    UIButton *jiesuanBUt;//结算按钮
    
    UIButton*rightButton;//编辑按钮
    
    UIButton *deleteBut;//删除按钮
    
    UILabel *hejiMoney;//合计金额
    UILabel *heji;//合计
     UILabel *qx;//全选
    
    
    NSMutableArray *HeadSecArray;
    
    
    //是否全选
    NSString *isQX;
    
    //用一个数组来承接被选择的数据
    NSMutableArray *SelectArray;//被选中的数据数组
    
    //product——id数组
    NSMutableArray *productIDarray;
    
    
    CGFloat k_keyboard_offsetY;
    CGFloat k_keyboardHeight;
    
    NSString *iphoneNum;//手机号码
    
    
    UIView *bootmView;
    
    
    NSMutableArray *Errorarray;//获取的错误的订单
    
    NSString *isbianji;
}
//TPKeyboardAvoidingTableView
@property(nonatomic,strong) UITableView *tableview;  //定义大表格
@end

@implementation gouwuCarVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"gouwuCarVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"gouwuCarVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationController.navigationBar.hidden=YES;
    
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
//    navcBar.frame=CGRectMake(0, 0, screenWidth, 60);
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"购物车";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
//    titleLabel.frame=CGRectMake(self.view.frame.size.width/2-70, 25, 140, 30);
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
//    leftButton.frame=CGRectMake(6, 60-6-28, 30, 28);
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];
    
    
    
    //编辑按钮
    rightButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
    rightButton.titleLabel.font=Font(15);
    [rightButton setSelected:NO];
    [rightButton addTarget:self action:@selector(bianji) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:rightButton];
//    rightButton.frame=CGRectMake(screenWidth-6-80, 60-6-28, 80, 28);
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-6);
        make.width.offset(60);
        make.height.offset(28);
        make.bottom.offset(-6);
    }];
    
    isbianji=@"false";//不是编辑状态
    
    SelectArray=[[NSMutableArray alloc]init];
    productIDarray=[[NSMutableArray alloc]init];
    
    //创建表格
    _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0,70, self.view.frame.size.width, self.view.frame.size.height-70-50+20) style:UITableViewStyleGrouped];
    
    _tableview.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    _tableview.separatorStyle=NO;
    [self.view addSubview:_tableview];
    
    //放置下拉上拉刷新控件
    __weak gouwuCarVC *weakSelf = self;
    
    // setup pull-to-refresh
    [self.tableview addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
    
    //刷新数据
    [self  insertRowAtTop];

    
    //下部按钮
    bootmView=[[UIView alloc]init];
    bootmView.backgroundColor=[UIColor whiteColor];
    bootmView.frame=CGRectMake(0,screenHeight-43, screenWidth, 43);
    [self.view addSubview:bootmView];
    
   
    isQX=@"false";
    
    //全部选择按钮
    quanxuanBUt=[UIButton buttonWithType:UIButtonTypeCustom];
    [quanxuanBUt setBackgroundImage:[UIImage imageNamed:@"ic_radio_btn_normal"] forState:UIControlStateNormal];
    [quanxuanBUt addTarget:self action:@selector(quanxuanBUtAction) forControlEvents:UIControlEventTouchUpInside];
    quanxuanBUt.frame=CGRectMake(10, 9, 25, 25);
    quanxuanBUt.layer.masksToBounds=YES;
    quanxuanBUt.layer.cornerRadius=12.5;
    [bootmView addSubview:quanxuanBUt];
    
    qx=[[UILabel alloc]init];
    qx.frame=CGRectMake(40, 7, 40, 30);
    qx.text=@"全选";
    qx.font=[UIFont systemFontOfSize:14];
    [bootmView addSubview:qx];
    
    
    //金额
    hejiMoney=[[UILabel alloc]init];
    hejiMoney.frame=CGRectMake(screenWidth-200, 7, 120, 30);
    hejiMoney.textColor=[UIColor colorWithRed:251.f/255.f green:87.f/255.f blue:60.f/255.f alpha:1];
    hejiMoney.text=@"￥0元";
    hejiMoney.font=[UIFont systemFontOfSize:14];
    [bootmView addSubview:hejiMoney];
    //合计：
    heji=[[UILabel alloc]init];
    heji.frame=CGRectMake(screenWidth-240, 7, 40, 30);
    heji.text=@"合计:";
    heji.font=[UIFont systemFontOfSize:14];
    [bootmView addSubview:heji];
    
    
    //结算
    jiesuanBUt=[[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-80,1, 80, 43)];
    jiesuanBUt.backgroundColor=[UIColor colorWithRed:251.f/255.f green:87.f/255.f blue:60.f/255.f alpha:1];
    [jiesuanBUt setTitle:@"结算" forState:UIControlStateNormal];
    jiesuanBUt.titleLabel.font=[UIFont systemFontOfSize:14];
    [jiesuanBUt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [jiesuanBUt addTarget:self action:@selector(jiesuanBUtAction) forControlEvents:UIControlEventTouchUpInside];
    [bootmView addSubview:jiesuanBUt];
    jiesuanBUt.hidden=NO;
    
    deleteBut=[[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-80,1, 80, 43)];
    deleteBut.backgroundColor=[UIColor colorWithRed:251.f/255.f green:87.f/255.f blue:60.f/255.f alpha:1];
    [deleteBut setTitle:@"删除" forState:UIControlStateNormal];
    deleteBut.titleLabel.font=[UIFont systemFontOfSize:14];
    [deleteBut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [deleteBut addTarget:self action:@selector(deleteButtAction) forControlEvents:UIControlEventTouchUpInside];
    [bootmView addSubview:deleteBut];
    deleteBut.hidden=YES;
    
    
    //分割线
    UIView *vwimg=[[UIView alloc]init];
    vwimg.backgroundColor=[UIColor colorWithRed:242.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1];
    vwimg.frame=CGRectMake(0, 0, screenWidth, 1);
    [bootmView addSubview:vwimg];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark -----------------监控键盘--------------------------
- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    k_keyboard_offsetY = keyboardRect.origin.y-8;
    k_keyboardHeight = keyboardRect.size.height;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.tableview.frame = CGRectMake(0, 70, screenWidth, screenHeight-70-k_keyboardHeight);
        
    }];
    
}

- (void)keyboardWillHide:(NSNotification *)notification{
    
    [UIView animateWithDuration:0.25 animations:^{
        self.tableview.frame = CGRectMake(0,70, screenWidth, screenHeight-70-50+20);
        
    }];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}

#pragma mark -----------------按钮点击事件--------------------------
//全选按钮
-(void)quanxuanBUtAction
{
   //全部选中
    
    if ([isQX isEqualToString:@"true"]) {
        
        isQX=@"false";
        
        for (int i=0; i<headArray.count; i++) {
            
            HeadSecArray[i]=@"false";
            
            NSArray *DA9=dicdata[headArray[i]];
            
            for (int j=0; j<DA9.count; j++) {
                
                dicdata[headArray[i]][j]=[dicdata[headArray[i]][j] mutableCopy];
                
                [dicdata[headArray[i]][j] setObject:@"false" forKey:@"isSelected"];
                
            }
            
        }
        
    }else{
        
    isQX=@"true";
        
    for (int i=0; i<headArray.count; i++) {
        
        HeadSecArray[i]=@"true";
        
        NSArray *DA9=dicdata[headArray[i]];
        
        for (int j=0; j<DA9.count; j++) {
            
            
            //将数据model取出
            gouwucartModel *gouwuMOD7=[[gouwucartModel alloc]initWith:DA9[j]];
            NSInteger status=gouwuMOD7.PRODUCT_STATUS.integerValue;
            
            if ([isbianji isEqualToString:@"false"]) {
                if (!(status==-1)) {
                    dicdata[headArray[i]][j]=[dicdata[headArray[i]][j] mutableCopy];
                    
                    [dicdata[headArray[i]][j] setObject:@"true" forKey:@"isSelected"];
                    
                }
                
            }else{
                
                dicdata[headArray[i]][j]=[dicdata[headArray[i]][j] mutableCopy];
                
                [dicdata[headArray[i]][j] setObject:@"true" forKey:@"isSelected"];
            }

            
            
    }

        
    }
    
}
    
    [self.tableview reloadData];
    
    [self loadBottomView];
    
}
//结算按钮
-(void)jiesuanBUtAction
{
    [SelectArray removeAllObjects];
    
    for (int i=0; i<headArray.count; i++) {
        
        NSArray *DE=dicdata[headArray[i]];
        
        for (int j=0; j<DE.count; j++) {
            
            NSMutableDictionary *dic=dicdata[headArray[i]][j];
            
            if ([dic[@"isSelected"] isEqualToString:@"true"]) {
                
                [SelectArray addObject:dic];
                
            }
            
            
        }
        
        
    }
    
if (SelectArray.count>0) {
    
     //先判断是否开通资金账户
    [Controller requestWithURL:ISFOUND jsondic:nil finishBlock:^(ClassData* data) {
        
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
//            "is_bind" = 1;
//            "is_found" = 1;
//            "is_main" = 1;
//            "main_mobile" = 0;
//            "main_name" = "";
            
            
//            "main_mobile":0,               只有当前账号绑定公司 并且不是主账号的时候 此字段才有手机号  默认为0
//            "is_bind":1,                       1已绑定   0未绑定
//            "is_main":0,                      1主账号   0子账号
//            "main_name":"",
//            "is_found":1                     1已开通   0未开通
            
            //是否开通
            NSString *is_found=[NSString  stringWithFormat:@"%@",data.data[@"is_found"]];
            NSInteger is_fd=is_found.integerValue;
            
            //是否是 主账号，子账号
            NSString *is_main=[NSString  stringWithFormat:@"%@",data.data[@"is_main"]];
            NSInteger is_ma=is_main.integerValue;
            //是否绑定
            NSString *is_bind=[NSString  stringWithFormat:@"%@",data.data[@"is_bind"]];
            NSInteger is_b=is_bind.integerValue;
            
            
            iphoneNum=data.data[@"main_mobile"];
            
            if (is_fd==1) {
            //已开通   判断库存是否充足
                
                [self checkuseblequantity];
                
            }else{
            //未开通
            //先判断是否开通     没开通的时候 判断是否有公司   然后再判断主子账号
                
                if (is_b==1) {
                    //绑定了公司  提示其开通资金账户
                    if (is_ma==1) {
                        //主账号
                        //初始化AlertView
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                        message:@"贵公司还没有开通资金账户！"
                                                                       delegate:self
                                                              cancelButtonTitle:@"开通资金账户"
                                                              otherButtonTitles:nil,nil];
                        alert.tag = 0;
                        [alert show];
                        
                    }else{
                        //子账号
                        //初始化AlertView
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                        message:[NSString stringWithFormat:@"贵公司还没有开通资金账户！\n请联系主账号，登录信用行网站或吆喝APP开通资金账户。\n主账号：%@  %@",data.data[@"main_name"],iphoneNum]
                                                                       delegate:self
                                                              cancelButtonTitle:@"取消"
                                                              otherButtonTitles:@"呼叫客服",@"呼叫主账号",nil];
                        alert.tag = 1;
                        [alert show];
                        
                    }
                    
                }else{
                       //未绑定公司  提示去绑定公司
                
                    //初始化AlertView
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                    message:@"您还没有“创建/加入”一家公司，无法查看求购"
                                                                   delegate:self
                                                          cancelButtonTitle:@"取消"
                                                          otherButtonTitles:@"加入公司",@"创建公司",nil];
                    
                    //这个属性继承自UIView，当一个视图中有多个AlertView时，可以用这个属性来区分
                    alert.tag = 3;
                    //只读属性，看AlertView是否可见
                    [alert show];

                    
                    
                }
                
                
            }
            
        }else
        {
            ALERTSHOW(data.message);
            
            
        }
    }];

}
    
}

//检查库存量
-(void)checkuseblequantity
{

    NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    
    NSMutableArray *productsArray=[[NSMutableArray alloc]init];
//    NSString *string = [productIDarray componentsJoinedByString:@","];
    
    for (int i=0; i<SelectArray.count; i++) {
        
        NSMutableDictionary *prdic1=[[NSMutableDictionary alloc]init];
        
        gouwucartModel *goucarM=[[gouwucartModel alloc]initWith:SelectArray[i]];
        
        [prdic1 setObject:goucarM.PRODUCT_ID forKey:@"product_id"];
        [prdic1 setObject:goucarM.QUANTITY forKey:@"quantity"];
        
        [productsArray addObject:prdic1];
        
    }
    
    NSString *proListjson=[productsArray JSONString];
    
    [di setValue:proListjson forKey:@"products"];//需要传一个数组

    //检查库存量
    [Controller requestWithURL:CheckUsebleQuantity jsondic:di finishBlock:^(ClassData* data) {
        
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            Errorarray=[[NSMutableArray alloc]init];
            Errorarray=data.data;
            if (Errorarray.count>0) {
                //说明有问题
                //初始化AlertView
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                message:@"您购买的货品中部分“已售罄”或“库存不足"
                                                               delegate:self
                                                      cancelButtonTitle:@"重新下单"
                                                      otherButtonTitles:nil];
                
                //这个属性继承自UIView，当一个视图中有多个AlertView时，可以用这个属性来区分
                alert.tag = 5;
                //只读属性，看AlertView是否可见
                [alert show];
            }else{
            //没问题  进入确认页面
            SureOrderVC *surevc=[[SureOrderVC alloc]init];
            surevc.OrderArray=SelectArray;
            surevc.isXianhuo=@"";
            [self.navigationController pushViewController:surevc animated:YES];
            }
            
        }else
        {
            ALERTSHOW(data.message);
            
        }
    }];


}


//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
      if (alertView.tag==0) {
        if (buttonIndex==0) {
            //开通资金账户
            zijinzhanghuVC*zijinVC=[[zijinzhanghuVC alloc]init];
            [self.navigationController pushViewController:zijinVC animated:YES];
            
        }
        
    }else if(alertView.tag==1){
        
        if (buttonIndex==1) {
            //呼叫客服
            
            //进入打电话页面
            UIWebView *webview = [[UIWebView alloc] init];
            [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel:4008850054"]]];
            [self.view addSubview:webview];

            
            
        }else if(buttonIndex==2){
            //呼叫主账号
    
            //进入打电话页面
            UIWebView *webview = [[UIWebView alloc] init];
            NSString *str=[NSString stringWithFormat:@"tel:%@",iphoneNum];
            [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:webview];

            
            
        }if (buttonIndex==0) {
            //取消
            
            
        }
        
    }else if(alertView.tag==3){
    
        if (buttonIndex==1) {
            
            //初始化AlertView
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请输入公司邀请码"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"确定",nil];
            
            alert.alertViewStyle=UIAlertViewStylePlainTextInput;
            //这个属性继承自UIView，当一个视图中有多个AlertView时，可以用这个属性来区分
            alert.tag = 4;
            //只读属性，看AlertView是否可见
            [alert show];
            
        }else if(buttonIndex==2){
            //创建公司
            CreateCompanyVC*creatVC=[CreateCompanyVC new];
            [self.navigationController pushViewController:creatVC animated:YES];
            
        }else if(buttonIndex==0){
            //取消
            
            
        }

        
    }else if(alertView.tag==4){
    
        //获取输入的邀请码
        UITextField*textField=[alertView textFieldAtIndex:0];
        NSDictionary*dic=@{@"COMPANY_ID":textField.text};
        [Controller requestWithURL:@"AppCompanyRegist/PostBindCompany?from=app" jsondic:dic finishBlock:^(ClassData *classData) {
            if ([classData.number integerValue]==0) {
                UIAlertView*alertViewCT=[[UIAlertView alloc]initWithTitle:@"加入公司" message:@"加入公司成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                //                    alertViewCT.alertViewStyle= UIAlertViewStyleDefault;
                alertViewCT.tag=20;
                [alertViewCT show];

                NSString *IDnumString=@"123456";

                [[NSUserDefaults standardUserDefaults] setObject:IDnumString forKey:ISCREATE];

                NSString *isregtype=@"0";
                [[NSUserDefaults standardUserDefaults] setObject:isregtype forKey:ISREGTYPE];



            }
            else{
                ALERTSHOW(classData.message);
                
            }
        }];

    }else if(alertView.tag==5){
        if (buttonIndex==0) {
            //重新下单   便利出错误的订单号，然后从已经选择的数组中将其移除  并将它设为无效勾选
            
            for (int j=0; j<Errorarray.count; j++) {
                
                NSString *errorproduct_id=[NSString stringWithFormat:@"%@",Errorarray[j][@"PRODUCT_ID"]];
                
                
                for (int i=0; i<headArray.count; i++) {
                    //先用一个数组承接字典里的小数组
                    NSArray *DA7=dicdata[headArray[i]];
                    
                    for (int j=0; j<DA7.count; j++) {
                        //先用一个数组承接字典里的小数组
                        //再用一个字典来承接数字里的小字典
                        NSDictionary *Adic7=DA7[j];
                        //将数据model取出
                        gouwucartModel *gouwuMOD7=[[gouwucartModel alloc]initWith:Adic7];
                        dicdata[headArray[i]][j]=[dicdata[headArray[i]][j] mutableCopy];
                        NSString *PRODUCT_ID=[NSString stringWithFormat:@"%@",gouwuMOD7.PRODUCT_ID];
                        if ([PRODUCT_ID isEqualToString:errorproduct_id]) {
                        
                        [dicdata[headArray[i]][j] setObject:@"false" forKey:@"isSelected"];
                        [dicdata[headArray[i]][j] setObject:@"-1" forKey:@"PRODUCT_STATUS"];
                            
                            //没有全选
                            isQX=@"false";
                            
                            if ([HeadSecArray[i] isEqualToString:@"true"]) {
                                
                                HeadSecArray[i]=@"false";
                            }else{
                                
                                
                            }

                            //刷新某一段
                            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:i];
                            [self.tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                            
                        }

                    }
                    
                }

            }
            
             [self loadBottomView];
            
        }
        
    
    }
    
    
    
}


//删除按钮
-(void)deleteButtAction
{

//    [SelectArray removeAllObjects];
    [productIDarray removeAllObjects];
    for (int i=0; i<headArray.count; i++) {
        
        NSArray *DE=dicdata[headArray[i]];
        
        for (int j=0; j<DE.count; j++) {
            
            NSMutableDictionary *dic=dicdata[headArray[i]][j];
            
            if ([dic[@"isSelected"] isEqualToString:@"true"]) {
                
                [productIDarray addObject:dic[@"PRODUCT_ID"]];
                
            }
            
        }
        
    }
    
   NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    
   NSString *string = [productIDarray componentsJoinedByString:@","];
    
    [di setValue:@"1433739374266387" forKey:@"memberId"];
    [di setValue:string forKey:@"productId"];
  if (productIDarray.count>0) {
        
    [Controller requestWithURL:DELETEPRODUCT jsondic:di finishBlock:^(ClassData* data) {
        
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            ALERTSHOW(@"删除成功！");
            //刷新数据
            [self  insertRowAtTop];
        }else
        {
            ALERTSHOW(data.message);
            
        }
    }];
    
    }

}


#pragma mark -----------------下拉刷新请求--------------------------
- (void)insertRowAtTop {
    __weak gouwuCarVC *weakSelf = self;
    
    [weakSelf.tableview beginUpdates];
    NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    [di setValue:@"1433739374266387" forKey:@"MEMBER_ID"];
    [Controller requestWithURL:SHOPPINGCART jsondic:di finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            //这是一个data数组
            NSMutableArray *dataArray=[NSMutableArray array];
            dataArray=data.data;
            //循环
//#warning test         
            //现将
//            BUSINESS_MODEL=0；的放在一组    BUSINESS_MODEL：0-自运营 10--第三方
            NSMutableArray *tureArray = [NSMutableArray array];
            NSMutableArray *falseArray = [NSMutableArray array];
            //            for (NSMutableDictionary *dataSource in gaiarray) {
            for (NSMutableDictionary *dataSource in dataArray) {
                //将数据model取出
                //                gouwucartModel *gouwuMOD=[[gouwucartModel alloc]initWith:dataSource];
                NSString *BUSINESS_MODEL=[NSString stringWithFormat:@"%@",dataSource[@"BUSINESS_MODEL"]];
                if ([BUSINESS_MODEL isEqualToString:@"10"]) {
                    [tureArray addObject:dataSource];
                    
                }else{
                    [falseArray addObject:dataSource];
                }
            }
            //处理false数组
            //取出第一个元素
            NSMutableArray *falseHandleArray = [NSMutableArray array];
            if (falseArray.count>=1) {
                NSMutableDictionary *firstModle = [falseArray firstObject];
                
                for (int i=0; i<falseArray.count; i++) {
                    
                    NSMutableDictionary *falseDic=[[NSMutableDictionary alloc]init];
                    falseDic=falseArray[i];
                    falseDic=[falseDic mutableCopy];
                    falseDic[@"SUPPLIER_NAME"] = firstModle[@"SUPPLIER_NAME"];
                    [falseHandleArray addObject:falseDic];
                }
            }
            
            //建立处理后的数组，
            NSMutableArray *allDataArray = [NSMutableArray arrayWithArray:tureArray];
            if (falseHandleArray.count!=0) {
                [allDataArray addObjectsFromArray:falseHandleArray];
            }
            dataArray=[NSMutableArray arrayWithArray:allDataArray];
            
//#warning test
            
            //定义一个大字典
            dicdata=[[NSMutableDictionary alloc]init];
            
            for (int i=0; i<dataArray.count; i++) {
                
                NSMutableDictionary *sd=[[NSMutableDictionary alloc]init];
                sd=dataArray[i];
                
                sd=[sd mutableCopy];
                [sd setValue:@"false" forKey:@"isSelected"];
                                
                if ([[dicdata allKeys] containsObject:sd[@"SUPPLIER_NAME"]]) {
                    
                    NSMutableArray *sma=[[NSMutableArray alloc]init];
                    sma=dicdata[sd[@"SUPPLIER_NAME"]];
                    [sma addObject:sd];
                    
                }else{
                
                    NSMutableArray *a=[NSMutableArray array];
                    [a addObject:sd];
                    
                    [dicdata setValue:a forKey:sd[@"SUPPLIER_NAME"]];
                    
                }
                
                    
            }
            //所有公司名称的数组(段头)
            headArray = dicdata.allKeys;
            HeadSecArray=[[NSMutableArray alloc]init];
            [HeadSecArray removeAllObjects];
            for (int h=0; h<headArray.count; h++) {
                [HeadSecArray addObject:@"false"];
            }
            //全选按钮
            isQX=@"false";
        
            //判断 是否  有 无数据
            if (headArray.count==0) {
                if (la) {
                    [la removeFromSuperview];
                }
                
                la=[[labelview alloc]init];
                [la setimage:@"gouwucheNew" tit:@"购物车空荡荡的" buttontit:@"去购物" frem:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
                la.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
                la.image.frame=CGRectMake((self.view.frame.size.width-120)/2, 50, 120, 97);
                la.label.frame=CGRectMake(50, 155, self.view.frame.size.width-100, 30);
                la.button.frame=CGRectMake(40, 195, self.view.frame.size.width-80, 40);
                la.delegate=self;
                [_tableview addSubview:la];
                bootmView.hidden=YES;
                
            }else{
                
                if (la) {
                    [la removeFromSuperview];
                }
                [self.tableview reloadData];
                
            }
            
            [self loadBottomView];
        }
        else
        {
            if (la) {
                [la removeFromSuperview];
            }
            
            la=[[labelview alloc]init];
            [la setimage:@"gouwucheNew" tit:@"购物车空荡荡的" buttontit:@"去购物" frem:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            la.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
            la.image.frame=CGRectMake((self.view.frame.size.width-120)/2, 50, 120, 97);
            la.label.frame=CGRectMake(50, 155, self.view.frame.size.width-100, 30);
            la.button.frame=CGRectMake(40, 195, self.view.frame.size.width-80, 40);
            la.delegate=self;
            [_tableview addSubview:la];
            bootmView.hidden=YES;

            
        }
    }];
    
    // 3. 结束刷新(相当于动画)
    [weakSelf.tableview endUpdates];
    
    [weakSelf.tableview.pullToRefreshView stopAnimating];
    
    
    
}
     
//去购物按钮代理（无数据的时候）
- (void)didClickButtonInBottomView{
    RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
    [rootTabBarViewController changeRootViewControllerTo:3];
    
}

//返回上一层
-(void)backLogin
{
    [self.navigationController popViewControllerAnimated:YES];
}

//编辑
-(void)bianji
{
    
    if (rightButton.isSelected==YES) {
        [rightButton setSelected:NO];
        //编辑
        heji.hidden=NO;
        hejiMoney.hidden=NO;
        jiesuanBUt.hidden=NO;
        deleteBut.hidden=YES;
        [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
        
        isbianji=@"false";
        
    }else{
        [rightButton setSelected:YES];
        //变成完成
        heji.hidden=YES;
        hejiMoney.hidden=YES;
        jiesuanBUt.hidden=YES;
        deleteBut.hidden=NO;
        
        [rightButton setTitle:@"完成" forState:UIControlStateNormal];
        
        isbianji=@"true";
    }

    //点击之后需要重新刷新选中状态
    
    isQX=@"false";
    
    for (int i=0; i<headArray.count; i++) {
        
        HeadSecArray[i]=@"false";
        
        NSArray *DA9=dicdata[headArray[i]];
        
        for (int j=0; j<DA9.count; j++) {
            
            dicdata[headArray[i]][j]=[dicdata[headArray[i]][j] mutableCopy];
            
            [dicdata[headArray[i]][j] setObject:@"false" forKey:@"isSelected"];
            
        }
        
    }

    
    [self.tableview reloadData];
    
    [self loadBottomView];

}

#pragma mark -----------------表格布局--------------------------

//返回单元格的分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return headArray.count;
}
//返回单元格的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSArray *arra=dicdata[headArray[section]];
    
    return arra.count;
    
}
//返回每个单元格要显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //指定cellIdentifier为自定义的cell
    static NSString *CellIdentifier = @"gouwuCarCell";
    
    //取出对应段落的数据
    
    //先用一个数组承接字典里的小数组
    NSArray *DA=dicdata[headArray[indexPath.section]];
    //再用一个字典来承接数字里的小字典
    NSDictionary *Adic=DA[indexPath.row];
    //将数据model取出
    gouwucartModel *gouwuMOD=[[gouwucartModel alloc]initWith:Adic];
    
    
    //自定义cell类
    gouwuCarCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    if (cell == nil) {
        //通过xib的名称加载自定义的cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"gouwuCarCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    
    
   //顶部字符串拼接
    NSString *toplable;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.SURFACE_CODE]) {
        toplable=[NSString stringWithFormat:@"%@ %@",gouwuMOD.PARENT_NAME,gouwuMOD.MATERIAL_CODE];
    }else{
        toplable=[NSString stringWithFormat:@"%@ %@/%@",gouwuMOD.PARENT_NAME,gouwuMOD.MATERIAL_CODE,gouwuMOD.SURFACE_CODE];
        
    }
    cell.topLable.text=toplable;
    
    //特惠图标
    NSInteger ispre=[gouwuMOD.SALES_PROMOTION integerValue];
    if (ispre==2) {
        cell.topTehuiImage.hidden=NO;
        cell.topTehuiImage.image=[UIImage imageNamed:@"ic_preferential"];
    }else{
        cell.topTehuiImage.hidden=YES;
    }

    
    
    NSString *guige=gouwuMOD.SPEC_CODE;
    
    //参厚
    NSString *canhou;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.REFERENCE_THICK ]) {
        canhou=@"";
    }else{
        canhou=[NSString stringWithFormat:@"(%@)",gouwuMOD.REFERENCE_THICK];
    }
    
    //边部
    NSString *bianbu;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.EDGE_NAME ]) {
        bianbu=@"";
    }else{
        
        bianbu=[NSString stringWithFormat:@"/%@",gouwuMOD.EDGE_NAME];
        
    }
    
    //等级
    NSString *dengji;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.LEVEL_NAME ]) {
        
        dengji=@"";
        
    }else{
        
        dengji=[NSString stringWithFormat:@"/%@",gouwuMOD.LEVEL_NAME];
        
    }
    
    
    //包装
    NSString *baozhuang;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.PACKAGE_TYPE ]) {
        
        baozhuang=@"";
        
    }else{
        //包装类型//(30,"裸包"),(10,"简包"),(20,"精包"),(0,"正常包装")
        NSInteger typ=gouwuMOD.PACKAGE_TYPE.integerValue;
        if (typ==30) {
            baozhuang=[NSString stringWithFormat:@"/裸包"];
        }else if(typ==20){
            baozhuang=[NSString stringWithFormat:@"/精包"];
        }else if(typ==10){
            baozhuang=[NSString stringWithFormat:@"/简包"];
        }else{
            
            baozhuang=[NSString stringWithFormat:@"正常包装"];
        }
    }
    
    
    //形状
    NSString *xinzhuang;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.SHAPE ]) {
        
        xinzhuang=@"";
        
    }else{
        
        xinzhuang=[NSString stringWithFormat:@"/%@",gouwuMOD.SHAPE];
        
    }

    //品名
    NSString *pingming;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.CATEGORY_NAME ]) {
        
        pingming=@"";
        
    }else{
    
        pingming=[NSString stringWithFormat:@"/%@",gouwuMOD.CATEGORY_NAME];
        
    }

    //仓库  生产商
    NSString *ck;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.HOUSE_NAME ]) {
        
        ck=@"";
        
    }else{
        
        ck=[NSString stringWithFormat:@"%@",gouwuMOD.HOUSE_NAME];
        
    }

    NSString *scs;
    if ([TongYong isBlankObjectAndStr:gouwuMOD.MANUFACTURER_NAME ]) {
        
        scs=@"";
        
    }else{
        
        scs=[NSString stringWithFormat:@"%@",gouwuMOD.MANUFACTURER_NAME];
        
    }

    cell.dizhiandcangku.text=[NSString stringWithFormat:@"%@     %@",ck,scs];
    
    //单位
    if ([gouwuMOD.PARENT_NAME isEqualToString:@"卷"]||[gouwuMOD.PARENT_NAME isEqualToString:@"卷材"]||[gouwuMOD.PARENT_NAME isEqualToString:@"带"]||[gouwuMOD.PARENT_NAME isEqualToString:@"带材"]) {
            dan=@"个";
        }else if([gouwuMOD.PARENT_NAME isEqualToString:@"板"]||[gouwuMOD.PARENT_NAME isEqualToString:@"板材"]){
            
            //判断库存
            if (gouwuMOD.USEABLE_QUANTITY.integerValue<10) {
                
                cell.danwei.text=@"库存紧张";
                cell.danwei.font=[UIFont systemFontOfSize:11];
                cell.danwei.textColor=[UIColor colorWithRed:251.f/255.f green:96.f/255.f blue:70.f/255.f alpha:1];
                
            }else{
            dan=@"张";
            }
        }else if([gouwuMOD.PARENT_NAME isEqualToString:@"管"]||[gouwuMOD.PARENT_NAME isEqualToString:@"管材"]){
            if (gouwuMOD.USEABLE_QUANTITY.integerValue<10) {
                
                cell.danwei.text=@"库存紧张";
                cell.danwei.font=[UIFont systemFontOfSize:11];
                cell.danwei.textColor=[UIColor colorWithRed:251.f/255.f green:96.f/255.f blue:70.f/255.f alpha:1];
                
            }else{
            dan=@"支";
            }
        }else if([gouwuMOD.PARENT_NAME isEqualToString:@"型"]||[gouwuMOD.PARENT_NAME isEqualToString:@"型材"]){
            if (gouwuMOD.USEABLE_QUANTITY.integerValue<10) {
                
                cell.danwei.text=@"库存紧张";
                cell.danwei.font=[UIFont systemFontOfSize:11];
                cell.danwei.textColor=[UIColor colorWithRed:251.f/255.f green:96.f/255.f blue:70.f/255.f alpha:1];
                
            }else{
            dan=@"个";
            }
        }
        cell.danwei.text=dan;
        cell.danwei.font=[UIFont systemFontOfSize:14];
        cell.danwei.textColor=Color153;
        

    NSInteger quantity=gouwuMOD.QUANTITY.integerValue;
    
    NSString *qu=[NSString stringWithFormat:@"%@",gouwuMOD.QUANTITY];
    cell.zhongliang.text=qu;
    
    //判断加号是否可用
    
    if (quantity==gouwuMOD.USEABLE_QUANTITY.integerValue) {
        cell.Addbut.backgroundColor=[UIColor colorWithRed:242.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1];
        cell.Addbut.userInteractionEnabled=NO;
    }
    
    //判断减号是否可用
    if (gouwuMOD.USEABLE_QUANTITY.integerValue==1||gouwuMOD.QUANTITY.integerValue==1) {
        cell.Redbut.backgroundColor=[UIColor colorWithRed:242.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1];
        cell.Redbut.userInteractionEnabled=NO;
    }

    [cell.Addbut addTarget:self action:@selector(AddbutAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.Redbut addTarget:self action:@selector(RedbutbutAction:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.zhongliang.delegate=self;
    
    [cell.zhongliang addTarget:self action:@selector(disMiss) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    //并且计算出金额
    //计算金额
    //单位类型
    NSInteger unitpric=gouwuMOD.PRICE_UNIT.integerValue;
    NSString *QUANTITY=[NSString stringWithFormat:@"%@",gouwuMOD.QUANTITY];
    NSString *weight=[NSString stringWithFormat:@"%@",gouwuMOD.USEABLE_WEIGHT];
    NSString *sale_price=[NSString stringWithFormat:@"%@",gouwuMOD.DISCOUNT_PRICE];
    
    NSDecimalNumber *quantityDM = [[NSDecimalNumber alloc] initWithString:QUANTITY];//个数
    NSDecimalNumber *weightDM = [[NSDecimalNumber alloc] initWithString:weight];//单个重量
    
    NSDecimalNumber *zongweightDM=[[NSDecimalNumber alloc]initWithString:@"0"];
    
    
    NSString *weightString;
    if (unitpric==10) {
        //元每吨
        NSDecimalNumber *qian = [[NSDecimalNumber alloc] initWithString:@"1000"];
        
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        zongweightDM=[zongweightDM decimalNumberByDividingBy:qian];
        weightString=[NSString stringWithFormat:@"%@吨",[NSString notRounding:zongweightDM afterPoint:3]];
        } else if (unitpric==20||unitpric==40) {
        //支或张
        zongweightDM=quantityDM;
        weightString=[NSString stringWithFormat:@"%@",[NSString notRounding:zongweightDM afterPoint:0]];
    } else {
        //千克
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        weightString=[NSString stringWithFormat:@"%@千克",[NSString notRounding:zongweightDM afterPoint:3]];
        
    }

    NSDecimalNumber *sale_priceDM = [[NSDecimalNumber alloc] initWithString:sale_price];
    
    NSDecimalNumber *everyON=[[NSDecimalNumber alloc]init];
    everyON = [sale_priceDM decimalNumberByMultiplyingBy:zongweightDM];
    cell.money.text=[NSString stringWithFormat:@"￥%@元",[NSString notRounding:everyON afterPoint:2]];
    
    
    if (unitpric==20||unitpric==40) {
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        weightString=[NSString stringWithFormat:@"%@千克",[NSString notRounding:zongweightDM afterPoint:3]];
    }
    
    
    NSString *bigTEXT;
    if ([gouwuMOD.CATEGORY_NAME isEqualToString:@"板"]||[gouwuMOD.CATEGORY_NAME isEqualToString:@"卷"]||[gouwuMOD.CATEGORY_NAME isEqualToString:@"带"]) {
        //		板卷   规格(参厚)/边部/等级/包装
        
        bigTEXT=[NSString stringWithFormat:@"%@%@%@%@ %@",guige,canhou,bianbu,dengji,weightString];
        
        
    }else{
        
        bigTEXT=[NSString stringWithFormat:@"%@%@%@",guige,pingming,xinzhuang];
    }
    
    cell.bigLable.text=bigTEXT;
    
    [cell.xuanzebut addTarget:self action:@selector(xuanzebutSelect:) forControlEvents:UIControlEventTouchUpInside];
    
    //cell的选中状态
    
    if([gouwuMOD.isSelected isEqualToString:@"true"]){
    
     [cell.xuanzebut setBackgroundImage:[UIImage imageNamed:@"ic_apply_quality_selected"] forState:UIControlStateNormal];
    }else{
    
    [cell.xuanzebut setBackgroundImage:[UIImage imageNamed:@"ic_radio_btn_normal"] forState:UIControlStateNormal];
        
    }
    
    NSInteger status=gouwuMOD.PRODUCT_STATUS.integerValue;
    if (status==-1&&[isbianji isEqualToString:@"false"]) {
        
        cell.backgroundColor=[UIColor colorWithRed:237.f/255.f green:237.f/255.f blue:237.f/255.f alpha:1];
        
        cell.xuanzebut.hidden=YES;
        cell.Addbut.hidden=YES;
        cell.danwei.hidden=YES;
        cell.zhongliang.hidden=YES;
        cell.Redbut.hidden=YES;
        cell.money.hidden=YES;
        cell.accessoryType=UITableViewCellAccessoryNone;
        
        
         UIButton  *shanchu=[UIButton buttonWithType:UIButtonTypeCustom];
        [shanchu setBackgroundImage:[UIImage imageNamed:@"najitong"] forState:UIControlStateNormal];
        [shanchu addTarget:self action:@selector(shanchuBUtAction:) forControlEvents:UIControlEventTouchUpInside];
        shanchu.frame=CGRectMake(self.view.frame.size.width-10-20, (cell.frame.size.height-20)/2+35, 20, 20);
        shanchu.layer.masksToBounds=YES;
        shanchu.layer.cornerRadius=12.5;
        [cell addSubview:shanchu];

    }

    return cell;

}
//cell上的删除按钮
-(void)shanchuBUtAction:(UIButton *)shanchubut
{
    UITableViewCell * cell = (UITableViewCell *)[shanchubut superview];
    NSIndexPath * path = [self.tableview indexPathForCell:cell];
    shanchubut.enabled=NO;
    
    //先用一个数组承接字典里的小数组
    NSArray *DA4=dicdata[headArray[path.section]];
    //再用一个字典来承接数字里的小字典
    NSMutableDictionary *Adic4=[[NSMutableDictionary alloc]init];
    Adic4=DA4[path.row];
    //将数据model取出
    gouwucartModel *gouwuMOD4=[[gouwucartModel alloc]initWith:Adic4];

    
    NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    
    [di setValue:@"1433739374266387" forKey:@"memberId"];
    [di setValue:gouwuMOD4.PRODUCT_ID forKey:@"productId"];
    [Controller requestWithURL:DELETEPRODUCT jsondic:di finishBlock:^(ClassData* data) {
        
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            
            ALERTSHOW(@"删除成功！");
            
            //刷新数据
            [self  insertRowAtTop];

            
        }else
        {
            shanchubut.enabled=YES;
            ALERTSHOW(data.message);
            
            
        }
    }];
    
    
    

}


#pragma mark -----------------数量控件按钮事件--------------------------
//加号按钮事件
-(void)AddbutAction:(id)sender
{
    
    UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath * path = [self.tableview indexPathForCell:cell];
   //先用一个数组承接字典里的小数组
    NSArray *DA4=dicdata[headArray[path.section]];
    //再用一个字典来承接数字里的小字典
    NSMutableDictionary *Adic4=[[NSMutableDictionary alloc]init];
    Adic4=DA4[path.row];
    //将数据model取出
    gouwucartModel *gouwuMOD4=[[gouwucartModel alloc]initWith:Adic4];
    
    NSInteger weighttext2=gouwuMOD4.QUANTITY.integerValue;
    
    weighttext2++;
    if (weighttext2>=gouwuMOD4.USEABLE_QUANTITY.integerValue) {
        
        weighttext2=gouwuMOD4.USEABLE_QUANTITY.integerValue;
        
    }
    
    dicdata[headArray[path.section]][path.row]=[dicdata[headArray[path.section]][path.row] mutableCopy];
    
   [dicdata[headArray[path.section]][path.row] setObject:[NSNumber numberWithInteger:weighttext2] forKey:@"QUANTITY"];
    

    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:path,nil] withRowAnimation:UITableViewRowAnimationNone];
    
    
    //增加购物车数
    NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    
    NSString *Numstring = [NSString stringWithFormat:@"%ld",(long)weighttext2];
    NSString *idproduct=[NSString stringWithFormat:@"%@",gouwuMOD4.PRODUCT_ID];
    
    [di setValue:@"1433739374266387" forKey:@"memberId"];
    [di setValue:idproduct forKey:@"productId"];
    [di setValue:Numstring forKey:@"quantity"];
    
    [Controller requestWithURL:CHANGEPRODUCT jsondic:di finishBlock:^(ClassData* data) {
        
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            
//            ALERTSHOW(@"修改数量成功！");
            
        }else
        {
            ALERTSHOW(data.message);
            
            
        }
    }];

    

    //判断是否是被选择的cell
    if ([gouwuMOD4.isSelected isEqualToString:@"true"]) {
        
        [self loadBottomView];
    }
    
    
    
}
//减号按钮事件
-(void)RedbutbutAction:(id)sender
{
    
    UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath * path = [self.tableview indexPathForCell:cell];
    //加号按钮
    //先用一个数组承接字典里的小数组
    NSArray *DA3=dicdata[headArray[path.section]];
    //再用一个字典来承接数字里的小字典
    NSDictionary *Adic3=DA3[path.row];
    //将数据model取出
    gouwucartModel *gouwuMOD3=[[gouwucartModel alloc]initWith:Adic3];

    NSInteger weighttext1=gouwuMOD3.QUANTITY.integerValue;
    
    weighttext1--;
    if (weighttext1<=1) {
    
        weighttext1=1;
        
    }
    
    dicdata[headArray[path.section]][path.row]=[dicdata[headArray[path.section]][path.row] mutableCopy];
    
    [dicdata[headArray[path.section]][path.row] setObject:[NSNumber numberWithInteger:weighttext1] forKey:@"QUANTITY"];

    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:path,nil] withRowAnimation:UITableViewRowAnimationNone];
    
    //减少购物车数
    NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    
    NSString *Numstring = [NSString stringWithFormat:@"%ld",(long)weighttext1];
    NSString *idproduct=[NSString stringWithFormat:@"%@",gouwuMOD3.PRODUCT_ID];
    
    [di setValue:@"1433739374266387" forKey:@"memberId"];
    [di setValue:idproduct forKey:@"productId"];
    [di setValue:Numstring forKey:@"quantity"];
    [Controller requestWithURL:CHANGEPRODUCT jsondic:di finishBlock:^(ClassData* data) {
        
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            
        }else
        {
            ALERTSHOW(data.message);
            
        }
    }];

    //判断是否是被选择的cell
    if ([gouwuMOD3.isSelected isEqualToString:@"true"]) {
        
        [self loadBottomView];
    }
    
}


#pragma mark -----------------输入框代理事件--------------------------


//文／沙瓦迪卡（简书作者）
//原文链接：http://www.jianshu.com/p/9fbfe84934cf
//著作权归作者所有，转载请联系作者获得授权，并标注“简书作者”。
//
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//
//{
//    UIView *view = textField.superview;
//    
//    while (![view isKindOfClass:[UITableViewCell class]]) {
//        
//        view = [view superview];
//        
//    }
//    
//    UITableViewCell *cell = (UITableViewCell*)view;
//    
//    CGRect rect = [cell convertRect:cell.frame toView:self.view];
//    
//    if (rect.origin.y / 2 + rect.size.height>=screenHeight-216) {
//        
//        _tableview.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
//        
//        [_tableview scrollToRowAtIndexPath:[_tableview indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
//        
//    }
//    
//    return YES;
//    
//}
//编辑框事件
//- (void)textFieldDidBeginEditing:(UITextField *)textField
//{
//    
//    UITableViewCell * cell = (UITableViewCell *)[[textField superview] superview];
//    NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];
//    
//    NSLog(@"%ld====%ld",(long)indexPath.section,(long)indexPath.row);
//    
////    CGRect rectInTableView = [_tableview rectForRowAtIndexPath:indexPath];
////    
////    [_tableview setContentOffset: CGPointMake( 0, rectInTableView.origin.y) animated: NO];
//    
////    
////        CGRect rect = [cell convertRect:cell.frame toView:self.view];
////    
////        if (rect.origin.y / 2 + rect.size.height>=screenHeight-216) {
////
////            [UIView animateWithDuration:0.25 animations:^{
////                self.view.frame=CGRectMake(0, -216, self.view.frame.size.width, self.view.frame.size.height);
////            }];
////        }
//    
//    
//    
//}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UITableViewCell * cell = (UITableViewCell *)[[textField superview] superview];
    NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];
    NSInteger nu=0;
    if(textField.text.length==0){
        textField.text=@"1";
    }
    
    nu=textField.text.integerValue;
    
    dicdata[headArray[indexPath.section]][indexPath.row]=[dicdata[headArray[indexPath.section]][indexPath.row] mutableCopy];
    
    [dicdata[headArray[indexPath.section]][indexPath.row] setObject:[NSNumber numberWithInteger:nu] forKey:@"QUANTITY"];

    
    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    
    //编辑购物车数量
    NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    
    NSString *Numstring = [NSString stringWithFormat:@"%ld",(long)nu];
    NSString *idproduct=[NSString stringWithFormat:@"%@",dicdata[headArray[indexPath.section]][indexPath.row][@"PRODUCT_ID"]];
    
    [di setValue:@"1433739374266387" forKey:@"memberId"];
    [di setValue:idproduct forKey:@"productId"];
    [di setValue:Numstring forKey:@"quantity"];
    
    [Controller requestWithURL:CHANGEPRODUCT jsondic:di finishBlock:^(ClassData* data) {
        
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {

        }else
        {
            ALERTSHOW(data.message);
            
            
        }
    }];

    
    
    
    if ([dicdata[headArray[indexPath.section]][indexPath.row][@"isSelected"] isEqualToString:@"true"] ) {
        
         [self loadBottomView];
    }
    
    
//    [UIView animateWithDuration:0.25 animations:^{
//        self.view.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
//    }];
    
    
    
    
    
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{  //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
    
    //获取控件所在位置
    
    UITableViewCell * cell = (UITableViewCell *)[[textField superview] superview];
    NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];
    //加号按钮
    //先用一个数组承接字典里的小数组
    NSArray *DA2=dicdata[headArray[indexPath.section]];
    //再用一个字典来承接数字里的小字典
    NSDictionary *Adic2=DA2[indexPath.row];
    //将数据model取出
    gouwucartModel *gouwuMOD2=[[gouwucartModel alloc]initWith:Adic2];
    
    if ([string isEqualToString:@"\n"])  //yes  按会车可以改变
        
    {
        return YES;
    }
    
    NSInteger weighttext;
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    weighttext=toBeString.integerValue;
    
    NSString *danwei;
    if ([gouwuMOD2.PARENT_NAME isEqualToString:@"卷"]||[gouwuMOD2.PARENT_NAME isEqualToString:@"卷材"]) {
        danwei=@"个";
    }else if([gouwuMOD2.PARENT_NAME isEqualToString:@"板"]||[gouwuMOD2.PARENT_NAME isEqualToString:@"板材"]){
        danwei=@"张";
    }else if([gouwuMOD2.PARENT_NAME isEqualToString:@"管"]||[gouwuMOD2.PARENT_NAME isEqualToString:@"管材"]){
        danwei=@"支";
    }else if([gouwuMOD2.PARENT_NAME isEqualToString:@"型"]||[gouwuMOD2.PARENT_NAME isEqualToString:@"型材"]){
        danwei=@"个";
    }


    if (weighttext >gouwuMOD2.USEABLE_QUANTITY.integerValue) {
        //如果输入框内容大于20则弹出警告
        NSString *str=[NSString stringWithFormat:@"现有库存：%ld%@，您购买量不可超过库存!", (long)gouwuMOD2.USEABLE_QUANTITY.integerValue,danwei];
        
        ALERTSHOW(str);
        
        return NO;
        
    }else{
    
//         gouwuMOD2.QUANTITY=[NSString stringWithFormat:@"%d",weighttext];
        
        dicdata[headArray[indexPath.section]][indexPath.row]=[dicdata[headArray[indexPath.section]][indexPath.row] mutableCopy];
        
        [dicdata[headArray[indexPath.section]][indexPath.row] setObject:[NSNumber numberWithInteger:weighttext] forKey:@"QUANTITY"];
    
    }
    
    return [self validateNumber:string];
    
//    return YES;
    
}
//只能输入数字的判断
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}


//键盘弹下
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

-(void)disMiss
{
    return;
}


#pragma mark -----------------设置段头段尾--------------------------
//用区尾当分割
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{

    return 15;

}

//区头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
//返回每一行单元格的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

//返回区头View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    QualityHeadView*headView=[[QualityHeadView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 30)];
    [headView.quTouBtn addTarget:self action:@selector(companySelect:) forControlEvents:UIControlEventTouchUpInside];
    
    headView.contentView.backgroundColor=[UIColor whiteColor];
    
    headView.quTouBtn.tag=section+100;
    
//    //判断是不是第三方  还是自营的 要不要显示供应商的名字
//    
//    //先用一个数组承接字典里的小数组
//    NSArray *DA=dicdata[headArray[section]];
//    //再用一个字典来承接数字里的小字典
//    NSDictionary *Adic=DA[0];
//    //将数据model取出
//    gouwucartModel *gouwuMOD=[[gouwucartModel alloc]initWith:Adic];
//    if ([gouwuMOD.SHOW_NAME isEqualToString:@"True"]) {
//        //展示供应商的名字
//         headView.companyLabel.text=headArray[section];
//    }else {
//       //展示仓库名  展示其中一个的仓库名称
//        headView.companyLabel.text=gouwuMOD.HOUSE_NAME;
//        
//    }
    
    headView.companyLabel.text=headArray[section];
    
    if ([HeadSecArray[section] isEqualToString:@"true"]) {
        
        [headView.quTouBtn setBackgroundImage:[UIImage imageNamed:@"ic_apply_quality_selected"] forState:UIControlStateNormal];
    }else{
    
        [headView.quTouBtn setBackgroundImage:[UIImage imageNamed:@"ic_radio_btn_normal"] forState:UIControlStateNormal];
    }
    
    
    
    return headView;
}

#pragma mark---------------------区头的代理方法
-(void)headerViewdelegate:(QualityHeadView *)header AndBtn:(UIButton *)btn
{
    
}

#pragma mark---------------------按钮点击事件
//区头公司圆圈的点击事件
-(void)companySelect:(UIButton*)quTou
{

//    UITableViewHeaderFooterView * cell = (UITableViewHeaderFooterView *)[[quTou superview] superview];
//    NSIndexSet *indexPath = [self.tableview indexPathForRowAtPoint:<#(CGPoint)#>];
    if ([HeadSecArray[quTou.tag-100] isEqualToString:@"false"]) {
        
        HeadSecArray[quTou.tag-100]=@"true";
        
        //这个时候要把这一段的所有cell都选上
         NSArray *DA9=dicdata[headArray[quTou.tag-100]];
        for (int i=0; i<DA9.count; i++) {
            
            //将数据model取出
            gouwucartModel *gouwuMOD7=[[gouwucartModel alloc]initWith:DA9[i]];
            NSInteger status=gouwuMOD7.PRODUCT_STATUS.integerValue;
            
            if ([isbianji isEqualToString:@"false"]) {
                if (!(status==-1)) {
                    dicdata[headArray[quTou.tag-100]][i]=[dicdata[headArray[quTou.tag-100]][i] mutableCopy];
                    [dicdata[headArray[quTou.tag-100]][i] setObject:@"true" forKey:@"isSelected"];
                    
                }

            }else{
            
                dicdata[headArray[quTou.tag-100]][i]=[dicdata[headArray[quTou.tag-100]][i] mutableCopy];
                [dicdata[headArray[quTou.tag-100]][i] setObject:@"true" forKey:@"isSelected"];
            
            }
            
            
            
            
        }
        
        
        //判断每段是不是都选上了
        NSInteger numcell=0;
        for (int j=0; j<HeadSecArray.count; j++) {
            if ([HeadSecArray[j] isEqualToString:@"true"]) {
                numcell++;
            }
        }
        
        if (numcell==HeadSecArray.count) {
            
            isQX=@"true";
            
        }else{
            //没有全选
            isQX=@"false";
            
        }

        
        
        
    }else{
        
         HeadSecArray[quTou.tag-100]=@"false";
        
        //没有全选
        isQX=@"false";

        //这个时候要把这一段的所有cell都选不选
        NSArray *DA10=dicdata[headArray[quTou.tag-100]];
        for (int j=0; j<DA10.count; j++) {
            
            dicdata[headArray[quTou.tag-100]][j]=[dicdata[headArray[quTou.tag-100]][j] mutableCopy];
            [dicdata[headArray[quTou.tag-100]][j] setObject:@"false" forKey:@"isSelected"];
            
        }

        
    }

    //刷新某一段
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:quTou.tag-100];
    [self.tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];

    [self loadBottomView];
    

}

//选择cell的选择按钮
-(void)xuanzebutSelect:(UIButton *)button
{

    UITableViewCell * cell = (UITableViewCell *)[[button superview] superview];
    NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];
    //先用一个数组承接字典里的小数组
    NSArray *DA7=dicdata[headArray[indexPath.section]];
    //再用一个字典来承接数字里的小字典
    NSDictionary *Adic7=DA7[indexPath.row];
    //将数据model取出
    gouwucartModel *gouwuMOD7=[[gouwucartModel alloc]initWith:Adic7];
    
    
    dicdata[headArray[indexPath.section]][indexPath.row]=[dicdata[headArray[indexPath.section]][indexPath.row] mutableCopy];
    
    if ([gouwuMOD7.isSelected isEqualToString:@"false"]) {
        
        [dicdata[headArray[indexPath.section]][indexPath.row] setObject:@"true" forKey:@"isSelected"];
        
        //判断有几个被选了，如果这个数组的都被选了，就将段头勾上。
        //计算几个被勾上
        NSInteger numsec=0;
         NSArray *DA8=dicdata[headArray[indexPath.section]];
        for (int i=0; i<DA8.count; i++) {
            NSDictionary *Adic8=DA8[i];
            gouwucartModel *gouwuMOD8=[[gouwucartModel alloc]initWith:Adic8];
            if ([gouwuMOD8.isSelected isEqualToString:@"true"]) {
                
                numsec++;
            }
        }
        
        if (numsec==DA8.count) {
            //证明全部被选上了  //刷新这一段变成勾
            HeadSecArray[indexPath.section]=@"true";
            //刷新某一段
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:indexPath.section];
            [self.tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            
            //判断每段是不是都选上了
            NSInteger numcell=0;
            for (int j=0; j<HeadSecArray.count; j++) {
                if ([HeadSecArray[j] isEqualToString:@"true"]) {
                    numcell++;
                }
            }
            
            if (numcell==HeadSecArray.count) {
                
                isQX=@"true";
                
            }else{
              //没有全选
               isQX=@"false";
                
            }
            
            
            
        }else{
        
    //刷新某一行
    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        }
    }else{
    
        [dicdata[headArray[indexPath.section]][indexPath.row] setObject:@"false" forKey:@"isSelected"];
        
        //没有全选
        isQX=@"false";
        
        if ([HeadSecArray[indexPath.section] isEqualToString:@"true"]) {
            
            HeadSecArray[indexPath.section]=@"false";
            //刷新某一段
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:indexPath.section];
            [self.tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            
        }else{
    //刷新某一行
    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

        
        }
        
        
    }

    
    
    [self loadBottomView];
    
    
    
    

}




//选中单元格时执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    // 取消选中状态
//    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
}



//刷新底部事件，计算数据
-(void)loadBottomView
{
//这里面分3步，1.全选按钮是否被选中  2.总共多少元     3.结算了多少个
    
    if ([isQX isEqualToString:@"true"]) {
        
        [quanxuanBUt setBackgroundImage:[UIImage imageNamed:@"ic_apply_quality_selected"] forState:UIControlStateNormal];
        
    }else{
    
       [quanxuanBUt setBackgroundImage:[UIImage imageNamed:@"ic_radio_btn_normal"] forState:UIControlStateNormal];
    }

//通过是否被选的cell来确定选择的个数
    
    NSInteger numse=0;
    
    NSDecimalNumber *zonggongM=[[NSDecimalNumber alloc]initWithString:@"0"];//总共的金额
    for (int i=0; i<headArray.count; i++) {
        
        NSArray *DA9=dicdata[headArray[i]];
        
        for (int j=0; j<DA9.count; j++) {
            
             gouwucartModel *gouwuMOD11=[[gouwucartModel alloc]initWith:dicdata[headArray[i]][j]];
            
             NSString *issec=gouwuMOD11.isSelected;
            
            if ([issec isEqualToString:@"true"]) {
                numse++;
                
                
                //并且计算出金额
                //计算金额
                //单位类型
                NSInteger unitpric=gouwuMOD11.PRICE_UNIT.integerValue;
                NSString *quantity=[NSString stringWithFormat:@"%@",gouwuMOD11.QUANTITY];
                NSString *weight=[NSString stringWithFormat:@"%@",gouwuMOD11.USEABLE_WEIGHT];
                NSString *sale_price=[NSString stringWithFormat:@"%@",gouwuMOD11.DISCOUNT_PRICE];
                
                NSDecimalNumber *quantityDM = [[NSDecimalNumber alloc] initWithString:quantity];//个数
                NSDecimalNumber *weightDM = [[NSDecimalNumber alloc] initWithString:weight];//单个重量

                NSDecimalNumber *zongweightDM=[[NSDecimalNumber alloc]initWithString:@"0"];
               
                if (unitpric==10) {
                    //元每吨
                    NSDecimalNumber *qian = [[NSDecimalNumber alloc] initWithString:@"1000"];
                    
                    zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
                    zongweightDM=[zongweightDM decimalNumberByDividingBy:qian];
                } else if (unitpric==20||unitpric==40) {
                    //支或张
                    zongweightDM=quantityDM;
                    
                } else {
                    //千克
                    zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
                    
                    
                }
                
                NSDecimalNumber *sale_priceDM = [[NSDecimalNumber alloc] initWithString:sale_price];
        
                NSDecimalNumber *everyON=[[NSDecimalNumber alloc]init];
                everyON = [sale_priceDM decimalNumberByMultiplyingBy:zongweightDM];
                
                zonggongM = [zonggongM decimalNumberByAdding:everyON];
                
            }
            
            
        }
        
    }
    NSString *butstr;
    if (numse==0) {
    butstr=[NSString stringWithFormat:@"结算"];
    }else{
    butstr=[NSString stringWithFormat:@"结算(%ld)",(long)numse];
    }
    
   [jiesuanBUt setTitle:butstr forState:UIControlStateNormal];
    
    //设定金额
    NSString *zgM=[NSString stringWithFormat:@"￥%@元",[NSString notRounding:zonggongM afterPoint:2]];
    hejiMoney.text=zgM;
    
    
}

@end
